using System;
using System.Text;
using System.Globalization;
using System.Runtime.InteropServices;

namespace needle.UI.Controls.Flat.Utilities.Win32
{
	public class SidLookup
	{
		#region Constructors

		public SidLookup()
		{
		}

		#endregion
		
		#region Methods
		
		[DllImport("advapi32.dll", CharSet=CharSet.Unicode)]
		public static extern bool ConvertStringSidToSidW(string stringSid, ref IntPtr sId);

		[DllImport("advapi32.dll", CharSet=CharSet.Unicode)]
		public static extern bool LookupAccountSidW(string lpSystemName,
			                                        IntPtr sId,
													StringBuilder Name,
													ref long cbName,
													StringBuilder domainName,
													ref long cbDomainName,
													ref int psUse);


		public string GetName(string sId)
		{
	        const int size = 255; 
			string domainName = String.Empty;
			string userName = String.Empty;
			long cbUserName = size;
			long cbDomainName = size;
			IntPtr ptrSid = new IntPtr(0);
			int psUse = 0;
			StringBuilder bufName = new StringBuilder(size);
			StringBuilder bufDomain = new StringBuilder(size);

	        if (ConvertStringSidToSidW(sId, ref ptrSid))
			{
				if (LookupAccountSidW(String.Empty, 
					                  ptrSid, bufName, 
									  ref cbUserName, bufDomain, 
									  ref cbDomainName, ref psUse))
				{
					userName = bufName.ToString();
					domainName = bufDomain.ToString();
					return String.Format(CultureInfo.CurrentCulture, @"{0}\{1}", domainName, userName);
				}
				else return String.Empty;
			}
			else return String.Empty;
		}

		#endregion
	}
}
